import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

// 相册信息类
class AlbumInfo {
  final String id;
  final String name;
  final int imageCount;
  final int videoCount;
  final String? thumbnailPath; // 本地缓存路径

  const AlbumInfo({
    required this.id,
    required this.name,
    this.imageCount = 0,
    this.videoCount = 0,
    this.thumbnailPath,
  });

  // 获取总数
  int get totalCount => imageCount + videoCount;

  // 根据照片/视频设置获取有效资源数量
  int getValidCount(bool includePhotos, bool includeVideos) {
    int count = 0;
    if (includePhotos) count += imageCount;
    if (includeVideos) count += videoCount;
    return count;
  }

  // JSON 序列化方法
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'imageCount': imageCount,
      'videoCount': videoCount,
      'thumbnailPath': thumbnailPath,
    };
  }

  // 从JSON创建
  factory AlbumInfo.fromJson(Map<String, dynamic> json) {
    return AlbumInfo(
      id: json['id'],
      name: json['name'],
      imageCount: json['imageCount'] ?? 0,
      videoCount: json['videoCount'] ?? 0,
      thumbnailPath: json['thumbnailPath'],
    );
  }

  // 创建拷贝
  AlbumInfo copyWith({
    String? id,
    String? name,
    int? imageCount,
    int? videoCount,
    String? thumbnailPath,
    bool clearThumbnail = false,
  }) {
    return AlbumInfo(
      id: id ?? this.id,
      name: name ?? this.name,
      imageCount: imageCount ?? this.imageCount,
      videoCount: videoCount ?? this.videoCount,
      thumbnailPath:
          clearThumbnail ? null : (thumbnailPath ?? this.thumbnailPath),
    );
  }
}

// 照片备份状态
class PhotoBackupState {
  // 自动备份状态
  final bool autoBackupPhotos;
  final bool autoBackupVideos;

  // 备份质量设置
  final bool originalBackup;
  final bool compressedBackup;

  // 网络设置
  final bool useMobileDataForPhotos;
  final bool useMobileDataForVideos;

  // 并行备份数量
  final int parallelBackupCount;

  // 相册选择状态
  final Map<String, bool> selectedAlbums;

  // 相册缓存 - 不在UI中使用，仅用于存储和恢复状态
  final List<AlbumInfo> albumCache;
  final DateTime? lastUpdateTime;

  PhotoBackupState({
    this.autoBackupPhotos = true,
    this.autoBackupVideos = true,
    this.originalBackup = false,
    this.compressedBackup = true,
    this.useMobileDataForPhotos = false,
    this.useMobileDataForVideos = false,
    this.parallelBackupCount = 3,
    Map<String, bool>? selectedAlbums,
    List<AlbumInfo>? albumCache,
    this.lastUpdateTime,
  }) : selectedAlbums = selectedAlbums ?? {},
       albumCache = albumCache ?? [];

  // 判断是否所有相册都被选中
  bool get isAllAlbumsSelected {
    if (selectedAlbums.isEmpty) return false;
    return selectedAlbums.values.every((selected) => selected);
  }

  // 创建新的状态实例
  PhotoBackupState copyWith({
    bool? autoBackupPhotos,
    bool? autoBackupVideos,
    bool? originalBackup,
    bool? compressedBackup,
    bool? useMobileDataForPhotos,
    bool? useMobileDataForVideos,
    int? parallelBackupCount,
    Map<String, bool>? selectedAlbums,
    List<AlbumInfo>? albumCache,
    DateTime? lastUpdateTime,
  }) {
    return PhotoBackupState(
      autoBackupPhotos: autoBackupPhotos ?? this.autoBackupPhotos,
      autoBackupVideos: autoBackupVideos ?? this.autoBackupVideos,
      originalBackup: originalBackup ?? this.originalBackup,
      compressedBackup: compressedBackup ?? this.compressedBackup,
      useMobileDataForPhotos:
          useMobileDataForPhotos ?? this.useMobileDataForPhotos,
      useMobileDataForVideos:
          useMobileDataForVideos ?? this.useMobileDataForVideos,
      parallelBackupCount: parallelBackupCount ?? this.parallelBackupCount,
      selectedAlbums: selectedAlbums ?? Map.from(this.selectedAlbums),
      albumCache: albumCache ?? List.from(this.albumCache),
      lastUpdateTime: lastUpdateTime ?? this.lastUpdateTime,
    );
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'autoBackupPhotos': autoBackupPhotos,
      'autoBackupVideos': autoBackupVideos,
      'originalBackup': originalBackup,
      'compressedBackup': compressedBackup,
      'useMobileDataForPhotos': useMobileDataForPhotos,
      'useMobileDataForVideos': useMobileDataForVideos,
      'parallelBackupCount': parallelBackupCount,
      'selectedAlbums': selectedAlbums,
      'albumCache': albumCache.map((album) => album.toJson()).toList(),
      'lastUpdateTime': lastUpdateTime?.millisecondsSinceEpoch,
    };
  }

  // 从JSON创建
  factory PhotoBackupState.fromJson(Map<String, dynamic> json) {
    return PhotoBackupState(
      autoBackupPhotos: json['autoBackupPhotos'] ?? true,
      autoBackupVideos: json['autoBackupVideos'] ?? true,
      originalBackup: json['originalBackup'] ?? false,
      compressedBackup: json['compressedBackup'] ?? true,
      useMobileDataForPhotos: json['useMobileDataForPhotos'] ?? false,
      useMobileDataForVideos: json['useMobileDataForVideos'] ?? false,
      parallelBackupCount: json['parallelBackupCount'] ?? 3,
      selectedAlbums:
          (json['selectedAlbums'] as Map<String, dynamic>?)?.map(
            (key, value) => MapEntry(key, value as bool),
          ) ??
          {},
      albumCache:
          (json['albumCache'] as List?)
              ?.map(
                (album) => AlbumInfo.fromJson(album as Map<String, dynamic>),
              )
              .toList() ??
          [],
      lastUpdateTime:
          json['lastUpdateTime'] != null
              ? DateTime.fromMillisecondsSinceEpoch(
                json['lastUpdateTime'] as int,
              )
              : null,
    );
  }
}

// 照片备份状态提供者
class PhotoBackupNotifier extends StateNotifier<PhotoBackupState> {
  PhotoBackupNotifier() : super(PhotoBackupState()) {
    // 初始化时加载缓存
    _loadFromStorage();
  }

  // 从存储加载状态
  Future<void> _loadFromStorage() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonStr = prefs.getString('photo_backup_state');

      if (jsonStr != null && jsonStr.isNotEmpty) {
        final jsonData = jsonDecode(jsonStr) as Map<String, dynamic>;
        state = PhotoBackupState.fromJson(jsonData);
      }
    } catch (e) {
      print('加载照片备份状态失败: $e');
    }
  }

  // 保存到存储
  Future<void> _saveToStorage() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonStr = jsonEncode(state.toJson());
      await prefs.setString('photo_backup_state', jsonStr);
    } catch (e) {
      print('保存照片备份状态失败: $e');
    }
  }

  // 生成相册缩略图并保存到本地
  Future<String?> _generateAndSaveThumbnail(
    Uint8List thumbnailData,
    String albumId,
  ) async {
    try {
      // 保存到本地
      final appDir = await getApplicationDocumentsDirectory();
      final thumbnailDir = Directory('${appDir.path}/album_thumbnails');
      if (!await thumbnailDir.exists()) {
        await thumbnailDir.create(recursive: true);
      }

      final thumbnailPath = '${thumbnailDir.path}/album_$albumId.jpg';
      final file = File(thumbnailPath);
      await file.writeAsBytes(thumbnailData);

      return thumbnailPath;
    } catch (e) {
      print('生成相册缩略图失败: $e');
      return null;
    }
  }

  // 更新相册缓存
  Future<void> updateAlbumCache(
    List<AssetPathEntity> albums,
    Map<String, Map<AssetType, int>> albumCounts,
    Map<String, Uint8List?> thumbnails,
  ) async {
    final List<AlbumInfo> newAlbumCache = [];

    for (final album in albums) {
      // 获取缓存的计数
      final counts = albumCounts[album.id];

      // 获取缩略图并保存到本地
      String? thumbnailPath;
      if (thumbnails[album.id] != null) {
        thumbnailPath = await _generateAndSaveThumbnail(
          thumbnails[album.id]!,
          album.id,
        );
      }

      // 创建相册信息
      final albumInfo = AlbumInfo(
        id: album.id,
        name: album.name,
        imageCount: counts?[AssetType.image] ?? 0,
        videoCount: counts?[AssetType.video] ?? 0,
        thumbnailPath: thumbnailPath,
      );

      newAlbumCache.add(albumInfo);
    }

    // 更新状态
    state = state.copyWith(
      albumCache: newAlbumCache,
      lastUpdateTime: DateTime.now(),
    );

    // 保存状态到存储
    await _saveToStorage();
  }

  // 设置自动备份照片状态
  void setAutoBackupPhotos(bool value) {
    state = state.copyWith(autoBackupPhotos: value);
    _saveToStorage();
  }

  // 设置自动备份视频状态
  void setAutoBackupVideos(bool value) {
    state = state.copyWith(autoBackupVideos: value);
    _saveToStorage();
  }

  // 设置原图备份状态
  void setOriginalBackup(bool value) {
    if (value) {
      state = state.copyWith(originalBackup: true, compressedBackup: false);
    } else {
      state = state.copyWith(originalBackup: false, compressedBackup: true);
    }
    _saveToStorage();
  }

  // 设置压缩备份状态
  void setCompressedBackup(bool value) {
    if (value) {
      state = state.copyWith(compressedBackup: true, originalBackup: false);
    } else {
      state = state.copyWith(compressedBackup: false);
    }
    _saveToStorage();
  }

  // 设置使用手机流量备份照片状态
  void setUseMobileDataForPhotos(bool value) {
    state = state.copyWith(useMobileDataForPhotos: value);
    _saveToStorage();
  }

  // 设置使用手机流量备份视频状态
  void setUseMobileDataForVideos(bool value) {
    state = state.copyWith(useMobileDataForVideos: value);
    _saveToStorage();
  }

  // 设置并行备份数量
  void setParallelBackupCount(int value) {
    if (value == 3 || value == 5 || value == 10) {
      state = state.copyWith(parallelBackupCount: value);
      _saveToStorage();
    }
  }

  // 设置单个相册选择状态
  void setAlbumSelection(String albumId, bool selected) {
    final newSelectedAlbums = Map<String, bool>.from(state.selectedAlbums);
    newSelectedAlbums[albumId] = selected;
    state = state.copyWith(selectedAlbums: newSelectedAlbums);
    _saveToStorage();
  }

  // 初始化相册选择状态
  void initAlbumSelection(String albumId, bool defaultValue) {
    if (!state.selectedAlbums.containsKey(albumId)) {
      final newSelectedAlbums = Map<String, bool>.from(state.selectedAlbums);
      newSelectedAlbums[albumId] = defaultValue;
      state = state.copyWith(selectedAlbums: newSelectedAlbums);
      _saveToStorage();
    }
  }

  // 批量初始化相册选择状态
  void initAlbumsSelection(List<AssetPathEntity> albums, bool defaultValue) {
    final newSelectedAlbums = Map<String, bool>.from(state.selectedAlbums);
    for (final album in albums) {
      if (!newSelectedAlbums.containsKey(album.id)) {
        newSelectedAlbums[album.id] = defaultValue;
      }
    }
    state = state.copyWith(selectedAlbums: newSelectedAlbums);
    _saveToStorage();
  }

  // 切换所有相册选择状态
  void toggleAllAlbums() {
    final allSelected = state.isAllAlbumsSelected;
    final newSelectedAlbums = Map<String, bool>.from(state.selectedAlbums);

    for (final key in newSelectedAlbums.keys) {
      newSelectedAlbums[key] = !allSelected;
    }

    state = state.copyWith(selectedAlbums: newSelectedAlbums);
    _saveToStorage();
  }

  // 清空相册选择状态
  void clearAlbumSelections() {
    state = state.copyWith(selectedAlbums: {});
    _saveToStorage();
  }

  // 清除相册缓存数据
  void clearAlbumCache() {
    state = state.copyWith(albumCache: [], lastUpdateTime: DateTime.now());
  }

  // 将缩略图保存到文件，返回保存路径
  Future<String?> saveThumbnailToFile(
    String albumId,
    Uint8List thumbnailData,
  ) async {
    try {
      // 保存到本地
      final appDir = await getApplicationDocumentsDirectory();
      final thumbnailDir = Directory('${appDir.path}/album_thumbnails');
      if (!await thumbnailDir.exists()) {
        await thumbnailDir.create(recursive: true);
      }

      final thumbnailPath = '${thumbnailDir.path}/album_$albumId.jpg';
      final file = File(thumbnailPath);
      await file.writeAsBytes(thumbnailData);

      // 更新状态中相册的缩略图路径
      final List<AlbumInfo> updatedAlbumCache = [];
      for (var album in state.albumCache) {
        if (album.id == albumId) {
          updatedAlbumCache.add(album.copyWith(thumbnailPath: thumbnailPath));
        } else {
          updatedAlbumCache.add(album);
        }
      }

      // 只有在缓存中找到相册时才更新状态
      if (state.albumCache.any((album) => album.id == albumId)) {
        state = state.copyWith(albumCache: updatedAlbumCache);
        await _saveToStorage();
      }

      return thumbnailPath;
    } catch (e) {
      print('保存缩略图失败: $e');
      return null;
    }
  }

  // 设置相册缓存列表
  void setAlbumCache(List<AlbumInfo> albumInfoList) {
    // 合并现有缩略图路径
    final List<AlbumInfo> mergedAlbumInfoList = [];
    final Map<String, String?> existingThumbnailPaths = {
      for (var album in state.albumCache) album.id: album.thumbnailPath,
    };

    for (var albumInfo in albumInfoList) {
      // 优先使用新的缩略图路径，如果没有则尝试保留现有路径
      final String? thumbnailPath =
          albumInfo.thumbnailPath ?? existingThumbnailPaths[albumInfo.id];

      // 检查缩略图文件是否存在
      if (thumbnailPath != null) {
        final file = File(thumbnailPath);
        file.exists().then((exists) {
          if (!exists) {
            // 如果文件不存在，从缓存中移除路径
            final List<AlbumInfo> updatedCache = [];
            for (var album in state.albumCache) {
              if (album.id == albumInfo.id) {
                updatedCache.add(
                  album.copyWith(thumbnailPath: null, clearThumbnail: true),
                );
              } else {
                updatedCache.add(album);
              }
            }
            state = state.copyWith(albumCache: updatedCache);
            _saveToStorage();
          }
        });
      }

      mergedAlbumInfoList.add(albumInfo.copyWith(thumbnailPath: thumbnailPath));
    }

    state = state.copyWith(
      albumCache: mergedAlbumInfoList,
      lastUpdateTime: DateTime.now(),
    );
  }

  // 从AlbumInfo对象列表初始化相册选择状态
  void initAlbumsSelectionFromInfo(List<AlbumInfo> albums) {
    final newSelectedAlbums = Map<String, bool>.from(state.selectedAlbums);
    for (final album in albums) {
      if (!newSelectedAlbums.containsKey(album.id)) {
        newSelectedAlbums[album.id] = true; // 默认选中
      }
    }
    state = state.copyWith(selectedAlbums: newSelectedAlbums);
  }

  // 保存当前状态
  Future<void> saveState() async {
    await _saveToStorage();
  }
}

// 创建全局状态提供者
final photoBackupProvider =
    StateNotifierProvider<PhotoBackupNotifier, PhotoBackupState>((ref) {
      return PhotoBackupNotifier();
    });
